home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!ittpub!ittpub!nntp
- Newsgroups: comp.lang.c++
- Subject: Re: g++ warning about initialization of non-const obj& - help needed
- Message-ID: <1996Feb2.152455.1767@ittpub>
- From: wil@ittpub.nl (Wil Evers)
- Date: 2 Feb 96 15:24:54 WET
- References: <4eo63u$kr1@llnews.ll.mit.edu>
- Distribution: world
- Nntp-Posting-Host: lintilla
-
- In article <4eo63u$kr1@llnews.ll.mit.edu> kappu@ll.mit.edu (Kalpana
- Subramanian) writes:
-
- > Hello g++ users,
- >
- > I have a function declared as such:
- >
- > func( obj &)
- >
- > I go to use it thus:
- >
- > func( obj.memberfunc() returning an obj);
- >
- > I get a warning -
- >
- > warning: initialization of non-const `obj &' from rvalue `obj'
- >
- > If I make a temporary obj, obj2 = obj.memberfunc()returning an obj,
- > and call func(obj2), it compiles.
- >
- > In reading the FAQ, I understand that temporaries inside function calls
- > that require conversion can get deleted before the conversion process,
- > thus causing erroneous results and should be avoided. However, in this
- > usage, the compiler should be able to make a reference from an object,
- > shouldn't it? Is it that the compiler will only want to make a const
- > reference from an object? The code I am compiling was all compiled under
- > previous versions of g++, and I wanted to upgrade it all. I am using
- > gcc/g++2.7.2 on a SunOS 4.1.4 platform.
- >
- > If this is obvious to anybody, could you please explain what the
- > issue is?
-
- The problem here is in func()'s prototype. func() takes a reference to a
- non-const obj, which is another way of saying that func() will probably
- modify the object passed to it - and may have been defined to do just
- that. However, since the modification will be done to a temporary that
- will subsequently cease to exist, func()'s modifications will be lost -
- and this could cause surprises.
-
- To give a simple example, supposing we have
-
- void inc(double& d)
- {
- d += 1.0;
- }
-
- and someone writes:
-
- main()
- {
- double d = 0.0;
- float f = 0.0;
- inc(d);
- inc(f);
- }
-
- Then the first call `inc(d)' *will* increment d, while to second call
- `inc(f)' *won't* increment f. Instead, a temporary double is created,
- which is then incremented and forgotten about. This is why the compiler
- warns about these things.
-
- - Wil
-